<script setup lang="ts">
// import { useColumns } from "./columns";
import DataTable from "./DataTable.vue";
import Search from "@iconify-icons/ep/search";
import { onMounted, ref } from "vue";
import { useRoute } from "vue-router";
import {
  Experiment,
  listPageExperiments,
  listExperiments,
  deleteInstance,
  getRunningExperiments
} from "@/api/LabExperimentApi";
import { listPlatforms, listParentPlatform } from "@/api/LabPlatformApi";
import { ElMessage } from "element-plus";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import AddFill from "@iconify-icons/ri/add-circle-line";
import dialogForm from "./components/DialogForm.vue";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import type {
  LoadingConfig,
  AdaptiveConfig,
  PaginationProps
} from "@pureadmin/table";

const { query } = useRoute();
// const platformName = ref(query.name ? query.name : "");
const searchValue = ref("");
const platformId = ref(query.id ? query.id : "");

const pagination = ref<PaginationProps>({
  currentPage: 1,
  pageSize: 20,
  total: 0,
  align: "right",
  background: true,
  small: false,
  pageSizes: [10, 20, 100]
});
const labPlatformData = ref([]);
const labExperimentData = ref<Experiment[]>([]);
const dataLoading = ref(true);
const formDialogVisible = ref(false);

const getLabPlatformData = async () => {
  try {
    //获取包括实验配置
    const pageResult = await listPlatforms();
    labPlatformData.value = pageResult.data;
    if (!platformId.value) {
      const defaultExpListConfigSelect = localStorage.getItem(
        "defaultExpListConfigSelect"
      );

      if (defaultExpListConfigSelect) {
        platformId.value = defaultExpListConfigSelect;
      } else {
        //如果没有传入platformId，labPlatformData按时间排序，取第一个

        labPlatformData.value.sort((a, b) => {
          const timeA = new Date(a.createTime);
          const timeB = new Date(b.createTime);

          return timeB - timeA;
        });
        platformId.value = labPlatformData.value[0].id;
      }
    }
    // platformName.value = labPlatformData.value.find(
    //   item => item.id === platformId.value
    // ).name;
    getLabExperimentDataByQuery(platformId.value as string, searchValue.value);
  } catch (e) {
    console.log(e);
  } finally {
    dataLoading.value = false;
  }
};

const getLabExperimentDataByQuery = async (expId: string, name: string) => {
  try {
    const params = {
      expId: expId,
      name: name,
      ...pagination.value
    };
    if (params.expId) {
      delete params.name;
    } else if (params.name) {
      delete params.expId;
    } else {
      delete params.expId;
      delete params.name;
    }
    const result = await listExperiments(params);
    labExperimentData.value = result.data;
    //遍历labExperimentData，如果item的state是20那disabled就为false
    const res = await getRunningExperiments();
    if (!res.errorCode) {
      if (res.data) {
        labExperimentData.value.forEach(item => {
          if (item.state === 10) {
            item.disabled = false;
          } else {
            item.disabled = true;
          }
        });
      }
    } else {
      message(`${res.message}`, { type: "error" });
    }

    pagination.value = {
      currentPage: 1,
      pageSize: pagination.value.pageSize,
      total: result.data ? result.total : 0
    };
  } catch (e) {
    console.log(e);
  } finally {
    dataLoading.value = false;
  }
};
const addNewExp = () => {
  formDialogVisible.value = true;
};

const handleDeleteItem = expId => {
  ElMessageBox.confirm(`确定删除实例${expId}`, "提示", {
    type: "warning"
  })
    .then(async () => {
      const ret = await deleteInstance(expId);
      if (!ret.errorCode) {
        getLabExperimentDataByQuery(
          platformId.value as string,
          searchValue.value
        );
        ElMessage.success("删除成功");
      } else {
        message(`停止失败，${ret.message}`, { type: "error" });
      }
    })
    .catch(() => {});
};
const changeDefaultExpListConfigSelect = () => {
  localStorage.setItem("defaultExpListConfigSelect", String(platformId.value));
};

onMounted(async () => {
  await getLabPlatformData();
  getLabExperimentDataByQuery(platformId.value as string, searchValue.value);
});
</script>
<template>
  <div>
    <el-card class="box-card m-4" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="font-medium">实验列表</span>
        </div>
      </template>
      <div class="w-full flex justify-between mb-4">
        <el-row>
          <el-select
            clearable
            v-model="platformId"
            placeholder="选择实验平台"
            style="width: 200px; margin-right: 30px"
            @change="
              getLabExperimentDataByQuery(platformId as string, searchValue);
              changeDefaultExpListConfigSelect();
            "
          >
            <el-option
              v-for="item in labPlatformData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-input
            style="width: 300px; margin-right: 12px"
            v-model="searchValue"
            placeholder="请输入实验实例名称"
            clearable
          >
            <template #suffix>
              <el-icon class="el-input__icon">
                <IconifyIconOffline
                  v-show="searchValue.length === 0"
                  :icon="Search"
                />
              </el-icon>
            </template>
          </el-input>
          <el-button
            @click="
              getLabExperimentDataByQuery(platformId as string, searchValue)
            "
            type="primary"
            >查询
          </el-button>
        </el-row>
      </div>
      <DataTable
        :labExperimentData="labExperimentData"
        :labPlatformData="labPlatformData"
        :newPagination="pagination"
        class="vue"
        @delete-item="handleDeleteItem"
      />
    </el-card>
    <dialogForm
      v-model:visible="formDialogVisible"
      @add-item="getLabPlatformData"
    />
  </div>
</template>

<style lang="scss" scoped>
.main-content {
  margin: 0 !important;
}
</style>
